package com.mingmen.supplier.activity;


import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mingmen.supplier.R;
import com.mingmen.supplier.adapter.CommodityAdapter;
import com.mingmen.supplier.adapter.NewDaiPeiSongAdapter;
import com.mingmen.supplier.adapter.NewOrderDetailAdapter;
import com.mingmen.supplier.base.BaseBean;
import com.mingmen.supplier.defineview.WeihuDialog;
import com.mingmen.supplier.http.callback.StringCallback;
import com.mingmen.supplier.httpconfig.HttpResponse;
import com.mingmen.supplier.immersionbar.ImmersionBar;
import com.mingmen.supplier.model.ImageModel;
import com.mingmen.supplier.model.NewOrderDetailModel;
import com.mingmen.supplier.util.GsonUtil;
import com.mingmen.supplier.util.SharePreferenceUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Response;

public class NewDaiPeiSongDetailActivity extends AppCompatActivity implements NewDaiPeiSongAdapter.OnItemClickListener {

    //返回按钮
    @BindView(R.id.text_return)
    TextView textReturn;


    @BindView(R.id.btn_receive)
    Button btn_login;

    @BindView(R.id.btn_reject)
    Button btn_reject;
    @BindView(R.id.layout_Distribution)
    LinearLayout layout_Distribution;

    String token;
    String billId;
    @BindView(R.id.address)
    TextView address;
    @BindView(R.id.restaurantName)
    TextView restaurantName;
    @BindView(R.id.orderDate)
    TextView orderDate;
    @BindView(R.id.shipping)
    TextView shipping;

    @BindView(R.id.total)
    TextView total;

    @BindView(R.id.applyMoney)
    TextView applyMoney;
    @BindView(R.id.text_billId)
    TextView text_billId;
    List<NewOrderDetailModel.DataBean.BillDetailsBean> dataBeanList = new ArrayList<>();
    String myShipping = "";
    String shippingFee = "";
    @BindView(R.id.recycle_detail)
    RecyclerView recycle_detail;
    NewDaiPeiSongAdapter newOrderDetailAdapter;
    @BindView(R.id.linear_return)
    LinearLayout linear_return;
    String partCancelFlag;
    String partArriveFlag;
    String partRefuseFlag;
    @BindView(R.id.btn_peisongdan)
    Button btn_peisongdan;
    private int resurtResurant = 100;
    WeihuDialog weihuDialog;
    @BindView(R.id.text_total)
    TextView text_total;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_newdaipeidetail);
        ButterKnife.bind(this);
        token = (String) SharePreferenceUtil.get(this, "token", "");
        billId = getIntent().getStringExtra("billId");
        partCancelFlag = getIntent().getStringExtra("partCancelFlag");
        partArriveFlag = getIntent().getStringExtra("partArriveFlag");
        partRefuseFlag = getIntent().getStringExtra("partRefuseFlag");
        ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f)
                .init();
        recycle_detail.setLayoutManager(new LinearLayoutManager(this));
        recycle_detail.setNestedScrollingEnabled(false);
        newOrderDetailAdapter = new NewDaiPeiSongAdapter(this, dataBeanList);
        recycle_detail.setAdapter(newOrderDetailAdapter);
        newOrderDetailAdapter.setOnItemClickListener(this);
        HttpResponse.getOrder(token, billId, partCancelFlag, partArriveFlag, partRefuseFlag, new StringCallback(this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                BaseBean baseBean = new BaseBean();
                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (baseBean.getCode() == 0) {
                    NewOrderDetailModel newOrderDetailModel = new NewOrderDetailModel();
                    newOrderDetailModel = GsonUtil.GsonToBean(s, NewOrderDetailModel.class);
                    restaurantName.setText(newOrderDetailModel.getData().get(0).getRestaurantName());
                    address.setText(newOrderDetailModel.getData().get(0).getAddress());
                    orderDate.setText(newOrderDetailModel.getData().get(0).getOrderDate());
                    if (newOrderDetailModel.getData().get(0).getShipping().equals("0")) {
                        shipping.setText("线下自取");
                    } else {
                        shipping.setText("商家配送");
                    }
                    total.setText(newOrderDetailModel.getData().get(0).getTotal());
                    applyMoney.setText("(￥" + newOrderDetailModel.getData().get(0).getApplyMoney() + "+配送费: " + "￥" + newOrderDetailModel.getData().get(0).getShippingFee() + "元" + ")");
                    text_billId.setText("订单编号: " + newOrderDetailModel.getData().get(0).getBillId());
                    dataBeanList.addAll(newOrderDetailModel.getData().get(0).getBillDetails());
                    myShipping = newOrderDetailModel.getData().get(0).getShipping();
                    shippingFee = newOrderDetailModel.getData().get(0).getShippingFee();
                    newOrderDetailAdapter.setDataList(dataBeanList);
                    text_total.setText(newOrderDetailModel.getData().get(0).getTotal());
                } else {
                    Toast.makeText(NewDaiPeiSongDetailActivity.this, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                }

            }
        });

    }


    @OnClick({R.id.text_return, R.id.btn_receive, R.id.btn_reject, R.id.layout_Distribution, R.id.linear_return, R.id.btn_peisongdan})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {

            case R.id.text_return:
            case R.id.linear_return:
                finish();
                break;
            case R.id.btn_receive:
                HttpResponse.deliverGoods(token, billId,"","","","", new StringCallback(NewDaiPeiSongDetailActivity.this) {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        BaseBean baseBean = new BaseBean();
                        baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                        if (baseBean.getCode() == 0) {
                            EventBus.getDefault().post(17);
                            finish();
                        } else {
                        }
                        Toast.makeText(NewDaiPeiSongDetailActivity.this, baseBean.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
                break;
            case R.id.btn_reject:
                break;
            case R.id.layout_Distribution:
//                startActivity(new Intent(NewDaiPeiSongDetailActivity.this, DistributionModeActivity.class));
                intent = new Intent(NewDaiPeiSongDetailActivity.this, DistributionModeActivity.class);
                intent.putExtra("shipping", myShipping);
                intent.putExtra("shippingFee", shippingFee);
                intent.putExtra("flag", "1");
                startActivityForResult(intent, resurtResurant);

                break;
            case R.id.btn_peisongdan:
                saveBileImage(token, billId);

                break;
        }
    }


    public void saveBileImage(String token, String billId) {
        HttpResponse.supplierOrderImage(token, billId, new StringCallback(NewDaiPeiSongDetailActivity.this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {

                BaseBean baseBean = new BaseBean();
                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (baseBean.getCode() == 0) {
                    Toast.makeText(NewDaiPeiSongDetailActivity.this, "保存成功", Toast.LENGTH_SHORT).show();

                } else {
                    Toast.makeText(NewDaiPeiSongDetailActivity.this, "当前无数据", Toast.LENGTH_SHORT).show();
                }

                Log.d("saveBileImage", s);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        ImageModel imageModel = new ImageModel();
                        imageModel = GsonUtil.GsonToBean(s, ImageModel.class);
                        Bitmap bp = returnBitMap(imageModel.getData().getData());
                        saveImageToPhotos(NewDaiPeiSongDetailActivity.this, bp);


                    }
                }).start();

//                MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), bitmap, "title", "description");
            }
        });
    }

    @Override
    public void onItemClickListener(View view, int pos, List<NewOrderDetailModel.DataBean.BillDetailsBean> myLiveList) {
        switch (view.getId()) {
            case R.id.shijia:
                weihuDialog = new WeihuDialog(this);
                weihuDialog.setVerifyClickListener("价格", new WeihuDialog.VerifyClickListener() {
                    @Override
                    public void cancel() {
                    }

                    @Override
                    public void send(String str) {
                        myLiveList.get(pos).setShijia(str);
                        newOrderDetailAdapter.notifyDataSetChanged();
                    }
                });
                weihuDialog.show();
                break;
            case R.id.arriveAmount:
                weihuDialog = new WeihuDialog(this);
                weihuDialog.setVerifyClickListener("价格", new WeihuDialog.VerifyClickListener() {
                    @Override
                    public void cancel() {
                    }

                    @Override
                    public void send(String str) {
                        myLiveList.get(pos).setArriveAmount(str);
                        newOrderDetailAdapter.notifyDataSetChanged();
                    }
                });
                weihuDialog.show();
                break;
        }
    }

    /**
     * 保存图片到本地相册
     */
    private void saveImageToPhotos(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
//            mHandler.obtainMessage(SAVE_FAILURE).sendToTarget();
            return;
        }
        // 最后通知图库更新
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);


    }


    /**
     * 将URL转化成bitmap形式
     *
     * @param url
     * @return bitmap type
     */
    public final static Bitmap returnBitMap(String url) {
        URL myFileUrl;
        Bitmap bitmap = null;
        try {
            myFileUrl = new URL(url);
            HttpURLConnection conn;
            conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    String text_peiSong;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == resurtResurant) {
            myShipping = data.getStringExtra("shipping");
            shippingFee = data.getStringExtra("shippingFee");
            text_peiSong = data.getStringExtra("text_peiSong");

            Log.d("text_peiSong", text_peiSong);
            shipping.setText(text_peiSong);
        }

    }
}




